package com.sokal.easycare.modules.trial.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sokal.easycare.common.config.Global;
import com.sokal.easycare.common.persistence.Page;
import com.sokal.easycare.common.web.BaseController;
import com.sokal.easycare.common.utils.StringUtils;
import com.sokal.easycare.modules.trial.entity.TrialRecord;
import com.sokal.easycare.modules.trial.service.TrialRecordService;

/**
 * 试算记录Controller
 * @author lihaipei
 * @version 2017-05-25
 */
@Controller
@RequestMapping(value = "${adminPath}/trial/trialRecord")
public class TrialRecordController extends BaseController {

	@Autowired
	private TrialRecordService trialRecordService;
	
	@ModelAttribute
	public TrialRecord get(@RequestParam(required=false) String id) {
		TrialRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = trialRecordService.get(id);
		}
		if (entity == null){
			entity = new TrialRecord();
		}
		return entity;
	}
	
	@RequiresPermissions("trial:trialRecord:view")
	@RequestMapping(value = {"list", ""})
	public String list(TrialRecord trialRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TrialRecord> page = trialRecordService.findPage(new Page<TrialRecord>(request, response), trialRecord); 
		model.addAttribute("page", page);
		return "modules/trial/trialRecordList";
	}

	@RequiresPermissions("trial:trialRecord:view")
	@RequestMapping(value = "form")
	public String form(TrialRecord trialRecord, Model model) {
		model.addAttribute("trialRecord", trialRecord);
		return "modules/trial/trialRecordForm";
	}

	@RequiresPermissions("trial:trialRecord:edit")
	@RequestMapping(value = "save")
	public String save(TrialRecord trialRecord, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, trialRecord)){
			return form(trialRecord, model);
		}
		trialRecordService.save(trialRecord);
		addMessage(redirectAttributes, "保存试算记录成功");
		return "redirect:"+Global.getAdminPath()+"/trial/trialRecord/?repage";
	}
	
	@RequiresPermissions("trial:trialRecord:edit")
	@RequestMapping(value = "delete")
	public String delete(TrialRecord trialRecord, RedirectAttributes redirectAttributes) {
		trialRecordService.delete(trialRecord);
		addMessage(redirectAttributes, "删除试算记录成功");
		return "redirect:"+Global.getAdminPath()+"/trial/trialRecord/?repage";
	}

}